#include "table.h"

/*
 * create and initial a table
 */
Table *new_table() {
    Table *table = (Table *) malloc(sizeof(Table));
    table->num_rows = 0;
    for (int i = 0; i < TABLE_MAX_ROWS; ++i) {
        table->pages[i] = NULL;
    }
    return table;
}


/*
 * free a table
 */
void free_table(Table *table) {
    for (int i = 0; table->pages[i]; ++i) {//here because linear pages ,so use table->page[i] to free a table
        free(table->pages[i]);
    }
    free(table);
}


/*
 * figure out where to read/write in memory for a particular row in a table
 */
void *row_slot(Table *table, uint32_t row_num) {
    uint32_t page_num =
            row_num / ROWS_PER_PAGE;//This step is to determine on which page of the table the target row is located.
    void *page = table->pages[page_num];//Obtain the corresponding page address.
    if (page == NULL) {//If the page address is NULL, it indicates that this page has not been allocated memory yet.
        page = table->pages[page_num] = malloc(PAGE_SIZE);
    }
    //Calculate the offset of a row within a page
    uint32_t row_offset = row_num % ROWS_PER_PAGE;//Calculate the num of row first
    uint32_t byte_offset = row_offset * ROW_SIZE;//Calculate the byte offset of the row lastly
    return page + byte_offset;//return the addr of the row we need
}

